package com.kongyz.config;

import com.kongyz.ConnectionWatcher;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.Charset;

/**
 * @author kongyz
 * @date 2018/7/19 22:05
 * @Description:
 */
public class ActiveKeyValueStore extends ConnectionWatcher {
    private static final Charset CHARSET=Charset.forName("UTF-8");

    public void write(String path,String value){
        try {
            Stat stat=zk.exists(path,false);
            if(stat==null){
                zk.create(path,value.getBytes(CHARSET), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            }else {
                zk.setData(path,value.getBytes(CHARSET),-1);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String read(String path, Watcher watcher){
        try {
            byte[] data=zk.getData(path,watcher,null);
            return new String(data,CHARSET);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
